var directAlipay = require('direct-alipay');
var tokenManager = require('../config/token_manager');
var db = require('../config/mongo_database');
var order = require('../route/order');
var redisClient = require('../config/redis_database').redisClient;
var logger = require('../config/log4js').logger('access');

directAlipay.config({
    seller_email: '13641892349', 
    partner: '2088702876958082', 
    key:'fh8m62ubr47ff524ei2yduyl3uimkn5q',
    notify_url: 'https://www.bgncode.com/aplipay/notify',
    return_url: 'https://www.bgncode.com/#/return'
    // notify_url: 'http://cat-vip.vicp.io/aplipay/notify',
   	// return_url: 'http://cat-vip.vicp.io/#/return'
}); 

exports.notify = function(req, res){
	var params = req.body;
	directAlipay.verify(params).then(function(result) {
		if(result){
			order.payOrder(params.out_trade_no, params.body)
			// return res.reply('支付成功');	
			return res.sendStatus(200);
		}    	
    }).catch(function(err) {
        logger.error(params.out_trade_no ,err)
    });
}

exports.pay = function(req, res) {
	var orderid = req.body.orderid || '';
	var userid = tokenManager.getUserId(req);
	logger.info('支付链接生成：', orderid, userid);
	order.getOrder(orderid, userid, function(status, order){
		logger.info('支付链接查询：',status, order);
		if(status){
			var url = directAlipay.buildDirectPayURL({
			    out_trade_no: order.orderid,
			    subject: "布谷鸟源码网-"+order.post.name,
			    body: order.pid+'-'+order.post.type+'-'+userid,
			    total_fee: order.payAmount  //0.01 //
			});
			return res.json({status:200, url:url});
		}
		return res.sendStatus(403);
	})
};

